package com.mxx.bu_yang.activity.on_line;

import android.content.Intent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.mxx.basic.server.RetrofitHelper;
import com.mxx.basic.server.enums.RequestEnum;
import com.mxx.basic.utils.MapUrlParamsUtils;
import com.mxx.basic.utils.SPUtils;
import com.mxx.basic.utils.ToastUtils;
import com.mxx.bu_yang.R;
import com.mxx.bu_yang.activity.LoginActivity;
import com.mxx.bu_yang.adapter.CheckAlreadyParentAdapter;
import com.mxx.bu_yang.common.CommonTitleActivity;
import com.mxx.bu_yang.dialog.DatePickDialog;
import com.mxx.bu_yang.response.CheckAlreadyResponse;
import com.mxx.common.config.ConstantsConfig;
import com.mxx.common.config.NetUrlConfig;
import com.mxx.common.observer.DefaultListObserver;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 作者：刘江飞
 * 时间：2020/10/14  16:25
 * 邮箱：642371742Z@qq.com
 * 描述：
 **/
public class GoodsCheckAlreadyActivity extends CommonTitleActivity {
    private TextView tv_checked;
    private TextView tv_go_check;
    private ImageView iv_calendar;
    private RecyclerView rv_check_parent;
    private CheckAlreadyParentAdapter parentAdapter;
    private int date_pick_show_count = 0;
    private final Map<String, String> paramsMap = new HashMap<>();

    @Override
    protected int getTitleType() {
        return TITLE_LEFT_BACK_MIDDLE_TITLE_RIGHT_TEXT;
    }

    /**
     * 获取当前页面的布局文件
     *
     * @return int
     */
    @Override
    public int getLayoutResId() {
        return R.layout.activity_goods_check_already;
    }

    @Override
    public void initView() {
        super.initView();
        iv_calendar = findViewById(R.id.iv_calendar);
        tv_checked = findViewById(R.id.tv_checked);
        tv_go_check = findViewById(R.id.tv_go_check);
        rv_check_parent = findViewById(R.id.rv_check_parent);
        initRecyclerView();
        paramsMap.put("begin", null);
        paramsMap.put("end", null);
        tv_title.setText("货品盘点");
        tv_right.setText("首页");

    }

    private void initRecyclerView() {
        LinearLayoutManager mManager = new LinearLayoutManager(this);
        mManager.setOrientation(RecyclerView.VERTICAL);
        rv_check_parent.setLayoutManager(mManager);
        parentAdapter = new CheckAlreadyParentAdapter(this, R.layout.adapter_goods_check_already);
        rv_check_parent.setAdapter(parentAdapter);
    }

    @Override
    public void initData() {
        super.initData();
        loadCheckAlready();
    }

    private void loadCheckAlready() {
        Map<String, String> paramsMap = getParamsMap();
        String json = "?" + MapUrlParamsUtils.getUrlParamsByMap(paramsMap);
        String baseUrl = (String) SPUtils.get(this, ConstantsConfig.BASE_URL, "");
        if (baseUrl == null || baseUrl.isEmpty()) {
            runOnUiThread(this::switchToLogin);
            return;
        }
        new RetrofitHelper
                .Builder()
                .baseUrl(baseUrl)
                .appendUrl("user/operationInventory/selectInventory" + json)
                .build()
                .observable(RequestEnum.METHOD_GET_NO_PARAMS)
                .subscribe(new DefaultListObserver(true, this) {
                    @Override
                    protected void handlerJsonArrayData(String arrayJson) {
                        List<CheckAlreadyResponse> list = paramsArrayJsonToList(arrayJson);
                        parentAdapter.setList(list);
                    }
                });

    }

    private Map<String, String> getParamsMap() {
        Map<String, String> map = new HashMap<>();
        int userId = getLoginInfo().userId;
        map.put("userId", String.valueOf(userId));
        String begin = paramsMap.get("begin");
        if (begin != null && !begin.isEmpty()) {
            map.put("begin", begin);
        }
        String end = paramsMap.get("end");
        if (end != null && !end.isEmpty()) {
            map.put("end", end);
        }
        return map;
    }

    private void switchToLogin() {
        ToastUtils.showToast(this, "IP为空，请到登录页重新设置IP");
        SPUtils.put(this, "login_info", "");
        SPUtils.put(this, ConstantsConfig.BASE_URL, "");
        Intent mIntent = new Intent(this, LoginActivity.class);
        mIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(mIntent);
        finish();
    }

    private List<CheckAlreadyResponse> paramsArrayJsonToList(String arrayJson) {
        List<CheckAlreadyResponse> list = new ArrayList<>();
        if (arrayJson != null && !arrayJson.isEmpty()) {
            list = new Gson().fromJson(arrayJson, new TypeToken<List<CheckAlreadyResponse>>() {
            }.getType());
        }
        return list;
    }


    @Override
    public void initListener() {
        super.initListener();
        iv_calendar.setOnClickListener(this);
        tv_checked.setOnClickListener(this);
        tv_go_check.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        if (view.getId() == R.id.iv_calendar) {
            date_pick_show_count++;
            if (date_pick_show_count % 2 == 1) {
                ToastUtils.showToast(this, "选择开始时间");
                showDatePickerDialog();
                return;
            }
            if (date_pick_show_count % 2 == 0) {
                ToastUtils.showToast(this, "选择结束时间");
                showDatePickerDialog();
                return;
            }
        }
        if (view.getId() == R.id.tv_checked) {
            loadGoods();
        }
        if (view.getId() == R.id.tv_go_check) {
            finish();
        }
    }

    private void showDatePickerDialog() {
        DatePickDialog mDatePicker = new DatePickDialog();
        mDatePicker.setOnSelectedDateListener((year, monthOfYear, dayOfMonth) -> {
            String start_time;
            String end_time;
            if (date_pick_show_count % 2 == 1) {
                start_time = year + "-" + monthOfYear + "-" + dayOfMonth + "  " + "00:00";
                paramsMap.put("begin", start_time);
            }
            if (date_pick_show_count % 2 == 0) {
                end_time = year + "-" + monthOfYear + "-" + dayOfMonth + "  " + "23:59";
                paramsMap.put("end", end_time);
            }
            loadCheckAlready();
        });
        mDatePicker.show(getSupportFragmentManager(), "DatePickDialog");
    }

    private void loadGoods() {
        parentAdapter.getData().clear();
        parentAdapter.notifyDataSetChanged();
        paramsMap.put("begin", null);
        paramsMap.put("end", null);
        loadCheckAlready();
    }

    @Override
    protected void titleRightTextClick() {
        super.titleRightTextClick();
        int CHECK_IN_RESULT_CODE = 0x1011;
        setResult(CHECK_IN_RESULT_CODE, getIntent());
        finish();
    }
}
